/**
 * 
 */
package hu.radai.jsfportal.servlet;

import hu.radai.jsfportal.log.LogManagerUtil;
import hu.radai.jsfportal.model.Constants;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author radai.tamas
 */
public class InitializerImpl implements Initializer {
	
	private ServletConfig servletConfig = null;
	/** Context path. Example: '\jsf-portal' or '\' */
	private static String CONTEXT_DIR = null;
	
	@Override
	public ServletConfig getServletConfig() {
		return this.servletConfig;
	}
	
	@Override
	public String getServletInfo() {
		return this.getClass().getName();
	}
	
	@Override
	public void init(final ServletConfig servletConfig) throws ServletException {
		this.servletConfig = servletConfig;
		CONTEXT_DIR = this.servletConfig.getServletContext().getContextPath()
										.replace("/", Constants.FILE_SEPARATOR);
		
		final String log4jConfigFile = Constants.TOMCAT_WEBAPPS_DIR + CONTEXT_DIR +
									   Constants.WEBAPP_CONFIG_DIR +
									   Constants.LOG_FILE_DEV;
		
		final String propertiesFile = Constants.TOMCAT_WEBAPPS_DIR + CONTEXT_DIR +
									  Constants.WEBAPP_CONFIG_DIR +
									  Constants.CONFIG_FILE_DEV;
		
		assert new File(log4jConfigFile).exists() : "Log4j config file is not exists";
		
		try {
			LogManagerUtil.init(log4jConfigFile);
			
			LogManagerUtil.debug(this.getClass(), "Load properties file ...");
			
			Constants.properties = new Properties();
			Constants.properties.loadFromXML(new FileInputStream(new File(propertiesFile)));
			
			LogManagerUtil.debug(this.getClass(),
								 "Load properties file is done ...");
		}
		catch (final Exception e) {
			e.printStackTrace();
		}
		
		LogManagerUtil.debug(this.getClass(),
							 "Load settings from properties file ... ");
		
		Constants.isDevelopMode = Boolean.valueOf(Constants.properties.getProperty("isDevelopMode"));
		
		LogManagerUtil.debug(this.getClass(),
							 "Load settings from properties file is done ... ");
		
		LogManagerUtil.info(this.getClass(), "Initialization is done ...");
	}
	
	@Override
	public void service(final ServletRequest arg0, final ServletResponse arg1)
					throws ServletException, IOException {
		final UnsupportedOperationException e = new UnsupportedOperationException(
																				  "Initializer servlet: service method is not supported");
		LogManagerUtil.warn(this.getClass(), e.getMessage(), e);
	}
	
	@Override
	public void destroy() {
		this.servletConfig = null;
	}
}
